package cn.keyvalue.ccf.common.http;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import cn.keyvalue.ccf.common.object.IPObject;
import net.sf.json.JSONObject;

public class IPUtils {

	// 从淘宝查询IP
	public static IPObject getIpInfo(String ip) throws Exception {
		String infoUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
		String jsonResponse = RequestUtils.urlToStr(infoUrl, "utf-8");

		JSONObject obj = JSONObject.fromObject(jsonResponse)
				.getJSONObject("data");
		
		IPObject retObj = new IPObject();
		if( obj.containsKey("country") )
		{
			retObj.setCountry(obj.getString("country"));
		}
		if( obj.containsKey("country_id") )
		{
			retObj.setCountry_id(obj.getString("country_id"));
		}
		if( obj.containsKey("area") )
		{
			retObj.setArea(obj.getString("area"));
		}
		if( obj.containsKey("area_id") )
		{
			retObj.setArea_id(obj.getString("area_id"));
		}
		if( obj.containsKey("region") )
		{
			retObj.setRegion(obj.getString("region"));
		}
		if( obj.containsKey("region_id") )
		{
			retObj.setRegion_id(obj.getString("region_id"));
		}
		if( obj.containsKey("city") )
		{
			retObj.setCity(obj.getString("city"));
		}
		if( obj.containsKey("city_id") )
		{
			retObj.setCity_id(obj.getString("city_id"));
		}
		if( obj.containsKey("isp") )
		{
			retObj.setIsp(obj.getString("isp"));
		}
		if( obj.containsKey("ip") )
		{
			retObj.setIp(obj.getString("ip"));
		}
		
		return retObj;
	}
	
	public static String getIP(HttpServletRequest request) {	
		
		//1.mm
		String ip = request.getRemoteAddr();
		String mmgatewap = "221.179.8.110";
		String mmgatewap2 = "127.0.0.1";
		if( StringUtils.equals(ip, mmgatewap) || StringUtils.equals(ip, mmgatewap2) )
		{
			String ipaddress = request.getHeader("X-Forwarded-For");
			if (ipaddress == null || ipaddress.length() == 0
					|| StringUtils.equalsIgnoreCase("unknown", ipaddress)) {
				ipaddress = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ipaddress == null || ipaddress.length() == 0
					|| StringUtils.equalsIgnoreCase("unknown", ipaddress)) {
				ipaddress = request.getHeader("x-forwarded-for");
			}
			if (ipaddress == null || ipaddress.length() == 0
					|| StringUtils.equalsIgnoreCase("unknown", ipaddress)) {
				ipaddress = request.getHeader("Proxy-Client-IP");
			}
			if (ipaddress == null || ipaddress.length() == 0
					|| StringUtils.equalsIgnoreCase("unknown", ipaddress)) {
				ipaddress = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ipaddress == null || ipaddress.length() == 0
					|| StringUtils.equalsIgnoreCase("unknown", ipaddress)) {
				ipaddress = request.getRemoteAddr();
			} else {
				// get first ip 192.168.1.110 from: X-Forwarded-For：192.168.1.110,
				// 192.168.1.120, 192.168.1.130, 192.168.1.100
				ipaddress = StringUtils.deleteWhitespace(ipaddress);
				String[] ipaddrlist = ipaddress.split(",");
				
				int pos = ArrayUtils.indexOf(ipaddrlist, mmgatewap);
				if( pos > 0 )
				{
					ipaddress = ipaddrlist[pos-1];
				}
				else
				{
					if (ipaddrlist.length > 1) {
						ipaddress = ipaddrlist[ipaddrlist.length-1];
					}
					
					//只有一个的情况，不使用
					if( ipaddress.length()==1 )
					{
						ipaddress = request.getRemoteAddr();
					}
				}
			}
			if (ipaddress.length() >= 128) {
				ipaddress = ipaddress.substring(0, 127);
			}
			
			return ipaddress;
		}		
		//2.其他
		else
		{
			return ip;
		}
		
	}

	
	
	// 将127.0.0.1形式的IP地址转换成十进制整数，这里没有进行任何错误处理  
    public static long ipToLong(String strIp) {  
        long[] ip = new long[4];  
        // 先找到IP地址字符串中.的位置  
        int position1 = strIp.indexOf(".");  
        int position2 = strIp.indexOf(".", position1 + 1);  
        int position3 = strIp.indexOf(".", position2 + 1);  
        // 将每个.之间的字符串转换成整型  
        ip[0] = Long.parseLong(strIp.substring(0, position1));  
        ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));  
        ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));  
        ip[3] = Long.parseLong(strIp.substring(position3 + 1));  
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];  
    }  
  
    // 将十进制整数形式转换成127.0.0.1形式的ip地址  
    public static String longToIP(long longIp) {  
        StringBuffer sb = new StringBuffer("");  
        // 直接右移24位  
        sb.append(String.valueOf((longIp >>> 24)));  
        sb.append(".");  
        // 将高8位置0，然后右移16位  
        sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));  
        sb.append(".");  
        // 将高16位置0，然后右移8位  
        sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));  
        sb.append(".");  
        // 将高24位置0  
        sb.append(String.valueOf((longIp & 0x000000FF)));  
        return sb.toString();  
    } 
    
    
	public static void main(String[] args) throws Exception{
		System.out.println(ipToLong( "223.252.128.0" ));

	}

}
